package iwpl.project.servlet;

import iwpl.project.dao.AccountsDAO;
import iwpl.project.dao.ApartmentsDAO;
import iwpl.project.dao.AreasDAO;
import iwpl.project.dao.EmployeesDAO;
import iwpl.project.dao.EquipmentsDAO;
import iwpl.project.dao.RoleDetailsDAO;
import iwpl.project.dao.RolesDAO;
import iwpl.project.entities.Accounts;
import iwpl.project.entities.Apartments;
import iwpl.project.entities.Areas;
import iwpl.project.entities.Employees;
import iwpl.project.entities.Equipments;
import iwpl.project.entities.RoleDetails;
import iwpl.project.entities.Roles;
import iwpl.project.entitymanagerhelper.EntityManagerHelper;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.List;

import javax.mail.Session;
import javax.management.relation.Role;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.omg.CORBA.Request;

import sun.net.www.content.audio.aiff;

public class Control_Account extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public Control_Account() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doDelete method of the servlet. <br>
	 *
	 * This method is called when a HTTP delete request is received.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doDelete(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		/*response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out
				.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("    This is ");
		out.print(this.getClass());
		out.println(", using the GET method");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();*/
		doProcess(request,response);
	}
	public static void ExecuteControl(String Control, Accounts acc)
	{
		//TODO add code here
		AccountsDAO dao = new AccountsDAO();
		
		if(Control == "Save")
		{
			EntityManagerHelper.beginTransaction();
			dao.save(acc);
			EntityManagerHelper.commit();
		}
		
		
		if(Control == "Update")
		{
			EntityManagerHelper.beginTransaction();
			dao.update(acc);
			EntityManagerHelper.commit();
		}
		
		if(Control == "Delete")
		{
			EntityManagerHelper.beginTransaction();
			dao.delete(acc);
			EntityManagerHelper.commit();
		}
	}
	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void CheckRole(Integer role,HttpServletRequest request,HttpServletResponse response)
	{
		
		
		HttpSession  session1 = request.getSession(true);
		RoleDetailsDAO rda = new  RoleDetailsDAO();
		if(role !=0)
		{
			List<RoleDetails> rol = rda.findByProperty("RoleID",role);
				int formid = 0;
				for(Iterator<RoleDetails> it = rol.iterator();it.hasNext();)
				{
					RoleDetails RD = (RoleDetails)it.next();
					formid = RD.getForms().getId();
					if(formid == 1)
					{
						String a = "active";
						session1.setAttribute("Manage_Account",a);
					}
					if(formid == 2)
					{
						String a = "active";
						session1.setAttribute("Manage_Apartment",a);
					}
					if(formid == 3)
					{
						String a = "active";
						session1.setAttribute("Manage_Contract",a);
					}
					//
					if(formid == 4)
					{
						String a = "active";
						session1.setAttribute("Manage_Customer",a);
					}
					if(formid == 5)
					{
						String a = "active";
						session1.setAttribute("Manage_Departments",a);
					}
					if(formid == 6)
					{
						String a = "active";
						session1.setAttribute("Manage_Employee",a);
					}
					if(formid == 7)
					{
						String a = "active";
						session1.setAttribute("Manage_Equipment",a);
					}
					if(formid == 8)
					{
						String a = "active";
						session1.setAttribute("Manage_EquimentDetails",a);
					}
					if(formid == 9)
					{
						String a = "active";
						session1.setAttribute("Manage_EquipmentHistories",a);
					}
					if(formid == 10)
					{
						String a = "active";
						session1.setAttribute("Manage_Forms",a);
					}
					if(formid == 11)
					{
						String a = "active";
						session1.setAttribute("Manage_Offices",a);
					}
					if(formid == 12)
					{
						String a = "active";
						session1.setAttribute("Manage_RoleDetails",a);
					}
					if(formid == 13)
					{
						String a = "active";
						session1.setAttribute("Manage_Roles",a);
					}if(formid == 14)
					{
						String a = "active";
						session1.setAttribute("Manage_Vehicles",a);
					}
					else
					{
						String a = "active";
					}
				}
		}
		
	}
	public void doProcess(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
	{
		Accounts Acc=new Accounts();
		AccountsDAO dao=new AccountsDAO();
		
		int id=0;
		int uid=0;
		try {
			String action=request.getParameter("action");
			
			if(request.getParameter("id")!=null)
				id=Integer.parseInt(request.getParameter("id"));
			
			// Account id update
			if(request.getParameter("sAid")!=null)
				uid=Integer.parseInt(request.getParameter("sAid"));
			
			
			String sname=request.getParameter("txtUserName");
			String ename=request.getParameter("txtEmployeeName");
			String apass =request.getParameter("sPass"); 
			
			Boolean sactive=Boolean.valueOf(request.getParameter("chkActive"));
			Accounts aInsert = new Accounts();
			String sStatus = request.getParameter("chkActive");
			if(sStatus==null)
				{
					Acc.setActive(false);
					aInsert.getActive();
				}
				
			else if(sStatus.toLowerCase().equals("on"))
				{
					Acc.setActive(true);
					aInsert.getActive();
				}
			
			
			
			String Pass =request.getParameter("txtPass");
			/*String sEmployeeID = request.getParameter("cboEmployeeID");*/
			String sRoleID = request.getParameter("cboRoleID");
			
			String spass=null;
			String active=null;
			Integer troleid = 1;
			RoleDetails rld;
		  HttpSession session = request.getSession(true);
			List<Accounts> ac = dao.findByUserName(sname);
			Accounts acc2 = null;
			for (Iterator<Accounts> it = ac.iterator(); it.hasNext();) {
				acc2 = (Accounts) it.next();
				spass =acc2.getPassword().toString();
				active = acc2.getActive().toString();
				troleid = acc2.getRoles().getId();
			}
			
			
	
			// logout
			if(action.equals("Logout"))
			{				
				session.removeAttribute("alogin");
				response.sendRedirect("../login.jsp");
			}
			//check login
			if(action.equals("Login"))
			{				
				if(ac.isEmpty())
					response.sendRedirect("../login.jsp?message='try do it again'");
				if(spass.equals(Pass)&&active.equals("true"))
					{
						 
					
						
						session.setAttribute("alogin", acc2);
					
						//CheckRole(troleid, request, response);
					
						response.sendRedirect("../index.jsp");
					}
				else	
					response.sendRedirect("../login.jsp?message='try do it again'");
			}
			//search
			if(action.equals("search"))
			{
					List<Accounts>list =null;
					String t = request.getParameter("empName");
					if(request.getParameter("empName") != null) {
						list = dao.findByUserName(request.getParameter("empName"));
						session.setAttribute("lSearch",list);
						response.sendRedirect("../Manage_Account.jsp");
					} else {
						list = dao.findAll();
						session.setAttribute("lSearch", list);
						response.sendRedirect("../Manage_Account.jsp");
					}	
				
				
			}
			//ChangePassword
			
			if(action.equals("ChangePassword"))
			{
				/*
				 * sAid
				 * txtOldPass
				 * txtNewpass
				 * confirm_password
				 * */
				
				if(request.getParameter("cID")!=null &&Integer.parseInt(request.getParameter("cID"))!=0)
					uid=Integer.parseInt(request.getParameter("cID"));
					{
						Accounts ac1 = dao.findById(uid);
							String opass = "";
							if(request.getParameter("txtOldPass")!=null)
							{
								if(ac1.getPassword()!=request.getParameter("txtOldPass").toString())
								{
									String t1 = request.getParameter("txtNewpass");
									String t2 = request.getParameter("confirm_password");
									if(t1.equals(t2))
									{																			
										ac1.setPassword(t1);
										EntityManagerHelper.beginTransaction();
										dao.save(ac1);
										EntityManagerHelper.commit();
										response.sendRedirect("../ChangePassword.jsp?message='changed'");
									}
									response.sendRedirect("../ChangePassword.jsp?message=check new pass");
								}
								
							}
							else
							{
								response.sendRedirect("../ChangePassword.jsp?message='invalid please check'");
								
							}
					}
			}
			//Resetpass
			if(action.equals("Resetpass"))
			{
				/*
				 * sAid
				 * txtOldPass
				 * txtNewpass
				 * confirm_password
				 * */
				
				if(request.getParameter("rAid")!=null &&Integer.parseInt(request.getParameter("rAid"))!=0)
					
					{
						uid=Integer.parseInt(request.getParameter("rAid"));
						Accounts ac1 = dao.findById(uid);
							
								if(request.getParameter("txtResetPassword").length()!=0)
								{
									String t1 = request.getParameter("txtResetPassword");
																												
										ac1.setPassword(t1);
										EntityManagerHelper.beginTransaction();
										dao.save(ac1);
										EntityManagerHelper.commit();
										response.sendRedirect("../ResetPassword.jsp?message=changed&sid="+uid);
									
								}
							else
							{
								response.sendRedirect("../ResetPassword.jsp?message=invalid please check&sid="+uid);
								
							}
					}
					else
					{
						response.sendRedirect("../Manage_Account.jsp?message='invalid please check'");
						
					}
				
			}
			//Delete
			if(action.equals("Delete")){
				Acc.setId(id);
				/*EntityManagerHelper.beginTransaction();
				dao.delete(Acc);
				EntityManagerHelper.commit();*/
				ExecuteControl("Delete",Acc);
				response.sendRedirect("../Manage_Account.jsp");
			}
			
			if(action.equals("Insert"))
				{
					Roles rle;
					
					if(request.getParameter("txtEmployeeID")!= null)
					{
						
						// check employee ID
						List<Accounts> testid = dao.findAll();
						
						int tid=0;
						for (Iterator<Accounts> it = testid.iterator(); it.hasNext();) 
						{
							Accounts acc1 = (Accounts) it.next();
							tid=acc1.getEmployees().getId();
							if(tid==Integer.parseInt(request.getParameter("txtEmployeeID")))
								{
									response.sendRedirect("../Insert_Account.jsp?message=EmployeeID was used");
								}
						}
						// gan' EmployeeID
						Integer ssEmployeeID = Integer.parseInt(request.getParameter("txtEmployeeID"));
						EmployeesDAO dao2 = new EmployeesDAO();
						Employees Emp = dao2.findById(ssEmployeeID);
						if(Emp==null)
							response.sendRedirect("../Insert_Account.jsp?message=EmployeeID invalid");
						if(Emp!=null)
						{
								// check username
								String testus="";
								for (Iterator<Accounts> it = ac.iterator(); it.hasNext();) 
									{
										Accounts acc1 = (Accounts) it.next();
										
										if(sname==acc1.getUserName())
										{
											response.sendRedirect("../Insert_Account.jsp?message=check username please");
										}
									}
								
									if(request.getParameter("cboRoleID")!= null)
									{
										Integer ssRoleID = Integer.parseInt(request.getParameter("cboRoleID"));
										RolesDAO dao1 = new RolesDAO();
										rle = dao1.findById(ssRoleID);	
									
										// Emid. RoleID, usename, password,active	
										
										aInsert.setUserName(sname);
										aInsert.setPassword(Pass);
										aInsert.setRoles(rle);
										aInsert.setEmployees(Emp);
										
										EntityManagerHelper.beginTransaction();
										dao.save(aInsert);
										EntityManagerHelper.commit();
										
										response.sendRedirect("../Insert_Account.jsp?message=inserted");
									}
									
						}
						
						response.sendRedirect("../Insert_Account.jsp?message=EmployeeID invalid");
						
						
					}
					response.sendRedirect("../Insert_Account.jsp?message=EmployeeID invalid not null");
				}
			
			
			
			if(action.equals("Update"))
				{
				Roles rle;
					if(request.getParameter("cboRoleID")!= null)
					{
						Integer ssRoleID = Integer.parseInt(request.getParameter("cboRoleID"));
						RolesDAO dao1 = new RolesDAO();
						rle = dao1.findById(ssRoleID);
						
						if(request.getParameter("SEmid")!= null)
						{
							Integer ssEmployeeID = Integer.parseInt(request.getParameter("SEmid"));
							EmployeesDAO dao2 = new EmployeesDAO();
							Employees Emp = dao2.findById(ssEmployeeID);
							
							Acc.setId(uid);
							Acc.setUserName(sname);
							
							Acc.setEmployees(Emp);
							Acc.setActive(sactive);
							Acc.setRoles(rle);
							Acc.setPassword(apass);
							
							
							EntityManagerHelper.beginTransaction();
							dao.update(Acc);
							EntityManagerHelper.commit();
							response.sendRedirect("../Manage_Account.jsp?message=updated");
						}
					}
					else
					{
						response.sendRedirect("../Manage_Account.jsp?message=updated fail");
					}
				}
			
		} catch (Exception e) {
			// TODO: handle exception
			System.out.print(e.getMessage());
		}  
				
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		/*response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out
				.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("    This is ");
		out.print(this.getClass());
		out.println(", using the POST method");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();*/
		doProcess(request,response);
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
